﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Mail;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Web;
using System.Web.Mail;
using Calendar.Logic.Core;
using Calendar.Logic.Log;
using Calendar.Logic.ObjectManager;
using Calendar.Logic.ObjectManager.Authorization;
using Calendar.Logic.ObjectModel;

namespace Calendar.Web.Core
{
    public static class EventSchedules
    {

        static private Thread _dispatch = null;
        private static int interval = 1000 * 60;

        static EventSchedules()
        {
            _dispatch = new Thread(Run);
        }

        static public void Start()
        {
            if (!_dispatch.IsAlive) _dispatch.Start();
        }

        static public void End()
        {
            if (_dispatch.IsAlive) _dispatch.Abort();
        }

        static private void Run()
        {
            while (_dispatch.IsAlive)
            {
                var events = EventNotificationManager.Instance.SelectNotSentOnNow(DateTime.Now, interval / (1000 * 60));
                var parameters = new Dictionary<string, string>();
                foreach (var ev in events)
                {
                    try
                    {
                        parameters["EventName"] = ev.Title;
                        string to = UserManager.Instance.SelectById(ev.User).Email;
                        try
                        {
                            EmailManager.Instance.Create("NoticeAboutEvent", to, parameters, null);
                            EventNotificationManager.Instance.SetSent(ev);
                        }

                        catch (ManagerException e)
                        {
                            LogManager.Log(DsLogLevel.ERROR, "Уведомление о торгах по расписанию", "Ошибка при обновлении записи: {0}", e.Message + "Id = " + ev.ID);
                        }

                        catch (Exception e)
                        {
                            LogManager.Log(DsLogLevel.ERROR, "Уведомление о торгах по расписанию", "Ошибка при создании email: {0}", e.Message + "Id = " + ev.ID);
                        }

                    }
                    catch (Exception exc)
                    {
                        LogManager.Log(DsLogLevel.ERROR, "Уведомление о торгах по расписанию", "Ошибка: {0}", exc.Message + (ev != null ? "Id = " + ev : ""));
                    }
                }
                Thread.Sleep(interval);
            }
        }

    }
}